package com.kitty.game.team.service;

import com.kitty.common.model.Pos;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.utils.ConcurrentHashSet;
import com.kitty.game.ServerService;
import com.kitty.game.activity.service.shidao.ShiDaoHandler;
import com.kitty.game.activity.service.task.TowerTaskHandler;
import com.kitty.game.config.Server;
import com.kitty.game.confirm.model.RequestTeamLeaderConfirm;
import com.kitty.game.confirm.model.ReturnTeamConfirm;
import com.kitty.game.difushidao.service.DiFuShiDaoPKService;
import com.kitty.game.difushidao.service.DiFuShiDaoService;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.ReqOtherMoveTo;
import com.kitty.game.enter.RespNotifyMisc;
import com.kitty.game.enter.RespPositionMove;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fight.service.BroadcastService;
import com.kitty.game.friend.model.RoleView;
import com.kitty.game.guard.service.GuardService;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.map.model.GroupMapParam;
import com.kitty.game.map.service.MapService;
import com.kitty.game.party.service.PartyService;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pk.service.PkService;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.scene.SceneManager;
import com.kitty.game.shidao.KuafuShidaoService;
import com.kitty.game.task.service.taskHandler.DugeonTaskHandler;
import com.kitty.game.team.message.*;
import com.kitty.game.team.model.*;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.SessionDataUtils;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.annotation.EventHandler;
import com.kitty.listener.event.*;
import com.kitty.mina.cache.SessionCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.task.ThreadLocalUtil;
import com.kitty.common.utils.StaticParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Predicate;


@Service
public class TeamService {
    private Logger logger = LoggerFactory.getLogger(TeamService.class);

    private static AtomicInteger atomicInteger = new AtomicInteger(1);
    @Autowired
    RoleService roleService;
    @Autowired
    GuardService guardService;
    @Autowired
    MapService mapService;
    @Autowired
    BroadcastService broadcastService;
    @Autowired
    NewTeamService newTeamService;

    /**
     * 处理角色升级事件 更新组队界面等级显示
     */
    @EventHandler(EventType.ROLE_LEVEL_UP)
    public void handleRoleLevelUpEvent(RoleLevelUpEvent roleLevelUpEvent) {
        Role role = roleLevelUpEvent.getRole();
        Team team = getTeam(role.getRoleId());
        if (team != null) {
            team.getList().forEach(member -> {
                if (member.getRoleId() == role.getRoleId()) {
                    member.setLevel(role.getLevel());
                }
            });
            updateTeamList(role);
            updateTeamListEX(team);
        }
    }

    /**
     * 登出
     */
    @EventHandler(EventType.LOGOUT)
    public void handleLogoutEvent(LogoutEvent logoutEvent) {
        Role role = logoutEvent.getRole();
        Team team = getTeam(role.getRoleId());
        /**掉线时换个队长*/
        if (team != null && getTeamCount(team) > 1 && team.isLeader(role.getRoleId())) {
            int toRoleId = 0;
            for (Member member : team.getList()) {
                if (member != null && member.getRoleId() != role.getRoleId() && member.isInTeam()
                        && roleService.isOnline(member.getRoleId())) {
                    toRoleId = member.getRoleId();
                }
            }
            if (toRoleId > 0) {
                changeLeader(role, toRoleId);
            }
        }
    }

    /**
     * 玩家主动退出
     */
    @EventHandler(EventType.LOGOUT_SELF)
    public void handleLogoutSelfEvent(LogoutSelfEvent logoutSelfEvent) {
        Role role = logoutSelfEvent.getRole();
        Team team = getTeam(role.getRoleId());
        if (team != null) {
            /**下线离队*/
            leave(role, false);
        }
    }

    public void handleRoleExpire(Role role) {
        if (role == null) {
            return;
        }
        Team team = getTeam(role.getRoleId());
        if (team != null) {
            /**离队*/
            leave(role, false);
        }
    }


    /**
     * 返回队伍
     */
    public void returnTeam(Role role) {
        Team team = getTeam(role.getRoleId());
        if (team == null) {
            return;
        }
        Role leader = roleService.getOnlinePlayer(team.getLeaderUid());
        if (leader == null) {
            return;
        }

        /**判断通天塔是否能归队*/
        if (!SpringUtils.getBean(TowerTaskHandler.class).isBackToTeam(team, role)) {
            return;
        }
        if (!SpringUtils.getBean(DugeonTaskHandler.class).isBackToTeam(team, role)) {
            return;
        }
        if (SpringUtils.getFightService().getFightByRoleId(role.getRoleId()) != null) {
            MessagePusher.pushMessage(role, new RespMsg("当前不能归队。"));
            return ;
        }
        if (SpringUtils.getFightService().getFightByRoleId(leader.getRoleId()) != null) {
            MessagePusher.pushMessage(role, new RespMsg("对方当前无法接受归队。"));
            return ;
        }
        for (Member member : team.getList()) {
            if (member.getRoleId() == role.getRoleId()) {
                member.setInTeam(true);
                break;
            }
        }
        saveTeam(team);
        updateTeamListEX(role);
        updateTeamList(role);
        fetchMember(leader, role);
        broadcastService.sendUpdateAppear(role);
        broadcastService.sendTitleInfo(role);
        sendAppearFormTeam(team);
    }


    /**
     * 发送位置移动
     */
    public void sendPositionMove(Role send, Role role) {
        MessagePusher.pushMessage(send, broadcastService.getMovePacket(role));
    }

    /**
     * 发送位置移动
     */
    public void sendPositionMove(IoSession session, Role role) {
        MessagePusher.pushMessage(session, broadcastService.getMovePacket(role));
    }

    /**
     * 取队伍ID
     */
    public static int getId() {
        return atomicInteger.getAndIncrement();
    }

    public void saveTeam(Team team) {
        if (team.getId() <= 0) {
            team.setId(getId());
        }
        SessionCache.TEAMS.put(team.getId(), team);
        for (Member member : team.getList()) {
            SessionCache.ROLE_TEAM.put(member.getRoleId(), team.getId());
        }
    }

    private void updateTeam(int status, int roleId) {
        Integer integer = SessionCache.ROLE_TEAM.get(roleId);
        if (integer == null) {
            return;
        }
        int teamId = integer;
        if (teamId <= 0) {
            return;
        }
        Team team = SessionCache.TEAMS.get(teamId);
        if (status == 1) {
            for (Member member : team.getList()) {
                if (member.getRoleId() == roleId) {
                    member.setInTeam(false);
                    break;
                }
            }
            saveTeam(team);
        }
    }


    private int getTeamId(int roleId) {
        Integer teamId = SessionCache.ROLE_TEAM.get(roleId);
        if (teamId == null) {
            return 0;
        }
        if (teamId <= 0) {
            return 0;
        }
        return teamId;
    }

    public Team getTeam(int roleId) {
        int teamId = getTeamId(roleId);
        return SessionCache.TEAMS.get(teamId);
    }

    public Team getTeamByTeamId(int teamId) {
        return SessionCache.TEAMS.get(teamId);
    }

    /**
     * 离开队伍
     */
    public void leave(Role role, boolean isKickOut) {
        leave(new RoleView(role), isKickOut);
    }


    /**
     * 离开队伍
     */
    public void leave(RoleView roleView, boolean isKickOut) {
        if (roleView == null) {
            return;
        }
        Team team = getTeam(roleView.getRoleId());
        if (team == null) {
            return;
        }
        Role role = roleView.getRole();
//        if (SpringUtils.getBean(ShiDaoHandler.class).isInShiDaoMap(role)){
//            MessagePusher.pushMessage(role,new RespNotifyMiscEx("试道进行中，无法离队"));
//            return;
//        }
        /**产生一个离开队伍事件*/
        if (role != null) {
            EventDispatcher.getInstance().fireEvent(new TeamLeaveEvent(EventType.TEAM_LEAVE, role, team.isLeader(roleView.getRoleId()), team.getList()));
        }
        boolean boo = quiltTeam(team, roleView.getRoleId());
        if (boo) {
            if (role != null) {
                broadcastService.sendTitleInfo(role);
                ////延迟一下不然会出错
                //////单独给自己发一下避免过迟群发
                Message titleInfo = broadcastService.getTitleInfo(role);
                MessagePusher.pushMessage(role, titleInfo);

                RespNotifyMisc respServer_onlineMsg = new RespNotifyMisc();
                respServer_onlineMsg.setMsg("队伍解散了。");//1639420980
                respServer_onlineMsg.setTime(new Long(System.currentTimeMillis() / 1000).intValue());
                MessagePusher.pushMessage(role, respServer_onlineMsg);


                RespClearnAllRequest respClearnAllRequest = new RespClearnAllRequest();
                respClearnAllRequest.setType("request_join");
                MessagePusher.pushMessage(role, respClearnAllRequest);

                RespClearnAllRequest respClearnAllRequest1 = new RespClearnAllRequest();
                respClearnAllRequest1.setType("request_team_leader");
                MessagePusher.pushMessage(role, respClearnAllRequest1);



                RespUpdateTeamList respUpdateTeamList = new RespUpdateTeamList();
                respUpdateTeamList.setList(new ArrayList<>());
                MessagePusher.pushMessage(role, respUpdateTeamList);
                updateTeamListEX(role);
                broadcastService.updateAppearance(role);

            }
        } else {
            // 广播给其他队员
            team = getTeamByTeamId(team.getId());
            Role leader = roleService.getOnlinePlayer(team.getLeaderUid());
            if (leader == null) {
                return;
            }
            broadcastService.sendTitleInfo(leader);
            updateTeamList(leader);
            updateTeamListEX(leader);
            if (role != null) {
                //
                RespUpdateTeamList respUpdateTeamList = new RespUpdateTeamList();
                respUpdateTeamList.setList(new ArrayList<>());
                MessagePusher.pushMessage(role, respUpdateTeamList);
                RespUpdateTeamListEX respUpdateTeamListEX = new RespUpdateTeamListEX();
                respUpdateTeamListEX.setList(new ArrayList<>());
                MessagePusher.pushMessage(role, respUpdateTeamListEX);
                broadcastService.sendTitleInfo(role);

                if (isKickOut) {
                    MessagePusher.pushMessage(role, new RespNotifyMiscEx("你被请离了队伍。"));

                }
            }
            //刷新我自己
            broadcastService.updateAppearance(role);
            //刷新我看到的别人
            sendTeamFormLeave(team,role);
            sendTeamChangeMsg(team, "#Y#<" + roleView.getName() + "#>#n离开了队伍。");
        }
        //刷新别人看到的我
        broadcastService.sendUpdateAppear(role);
        //队员之间刷新
        sendAppearFormTeam(team);
        SpringUtils.getBean(ShiDaoHandler.class).doAfterLeaveTeam(role, team);
        SpringUtils.getBean(DiFuShiDaoPKService.class).doAfterLeaveTeam(role, team);
    }


    /**
     * @param role
     */
    private void memberIn(Role role, Role leader) {
        ServerService serverService = SpringUtils.getBean(ServerService.class);
        Server server = serverService.getServer();
        RespFriendUpdatePartial updatePartial = new RespFriendUpdatePartial();
        updatePartial.setName(role.getName());
        updatePartial.setUpdate_type((short) 2);
        updatePartial.setType("6");
        ArrayList<FiedValue> arrayList = new ArrayList<>();
        {
            arrayList.add(new FiedValue(301,3,0));
            arrayList.add(new FiedValue(302,1,0));
            arrayList.add(new FiedValue(304,4,""));
            arrayList.add(new FiedValue(334,1,0));
            arrayList.add(new FiedValue(292,3,role.getRoleIcon()));
            arrayList.add(new FiedValue(31,2,role.getLevel()));
            arrayList.add(new FiedValue(3012,4,server.getSonName()));
            arrayList.add(new FiedValue(40,7,role.getRoleIcon()));
            arrayList.add(new FiedValue(290,3,0));
            arrayList.add(new FiedValue(33,4,role.getPartyName()));
            arrayList.add(new FiedValue(880,1,0));
            arrayList.add(new FiedValue(90,4,""));
            arrayList.add(new FiedValue(81,4,roleService.getFamilyName(role.getPolar())));
            arrayList.add(new FiedValue(36,4,role.getCurrTitle()));
            arrayList.add(new FiedValue(291,3,0));
            arrayList.add(new FiedValue(305,4,role.getGid()));
            arrayList.add(new FiedValue(27,3,0));
            arrayList.add(new FiedValue(194,1,1));

        }
        updatePartial.setList(arrayList);
        MessagePusher.pushMessage(leader, updatePartial);
    }

    /**
     * 新队员加入成功
     */
    public void JoinSuccess(Role role, Role leader) {
        ServerService serverService = SpringUtils.getBean(ServerService.class);
        Server server = serverService.getServer();//mapService.getServer(serverService.getPort(), serverService.getIp());
        RespFriendAddRole respFriendAddRole = new RespFriendAddRole();
        respFriendAddRole.setName(role.getName());
        respFriendAddRole.setType1((short) 1);
        respFriendAddRole.setType("6");
        respFriendAddRole.setLineName(server.getSonName());
        ArrayList<FiedValue> arrayList = new ArrayList<>();
        {
            arrayList.add(new FiedValue(301,3,0));
            arrayList.add(new FiedValue(302,1,0));
            arrayList.add(new FiedValue(304,4,""));
            arrayList.add(new FiedValue(334,1,0));
            arrayList.add(new FiedValue(292,3,role.getRoleIcon()));

            arrayList.add(new FiedValue(31,2,role.getLevel()));
            arrayList.add(new FiedValue(40,2,role.getRoleIcon()));
            arrayList.add(new FiedValue(3012,4,server.getSonName()));
            arrayList.add(new FiedValue(290,3,0));
            arrayList.add(new FiedValue(1,4,role.getName()));

            arrayList.add(new FiedValue(33,4,role.getPartyName()));
            arrayList.add(new FiedValue(90,4,""));
            arrayList.add(new FiedValue(880,1,0));
            arrayList.add(new FiedValue(36,4,role.getCurrTitle()));
            arrayList.add(new FiedValue(81,4,roleService.getFamilyName(role.getPolar())));

            arrayList.add(new FiedValue(291,3,0));
            arrayList.add(new FiedValue(305,4,role.getGid()));
            arrayList.add(new FiedValue(27,3,0));
            arrayList.add(new FiedValue(21,3,0));
            arrayList.add(new FiedValue(194,1,1));
        }
        respFriendAddRole.setList(arrayList);
        MessagePusher.pushMessage(leader, respFriendAddRole);
    }


    /**
     * 退出队伍
     */
    public boolean quiltTeam(Team team, int roleId) {
        SessionCache.ROLE_TEAM.remove(roleId);
        List<Member> list = team.getList();
        for (int i = 0; i < list.size(); i++) {
            Member member = list.get(i);
            if (member.getRoleId() == roleId) {
                list.remove(i);
                break;
            }
        }
        if (list.size() <= 0) {
            // 队伍没有成员
            SessionCache.TEAMS.remove(team.getId());
            return true;
        } else {
            list.get(0).setInTeam(true);//第一个人设置为队长
            return false;
        }
    }


    /**
     * 队伍成员刷新列表
     */
    private List<TeamMember> getTeamMemberList(Team team) {
        List<TeamMember> list = new ArrayList<>();
        for (Member member : team.getList()) {
            if (member == null) {continue; }
            if (!member.isInTeam()) {
                continue;
            }
            TeamMember teamMember = new TeamMember();
            teamMember.setGid(member.getGid());
            teamMember.setCard_name(member.getCardName());
            teamMember.setIcon(member.getIcon());
            teamMember.setRoleId(member.getRoleId());
            teamMember.setSuit_icon(member.getSuitIcon());
            teamMember.setWeapon_icon(member.getWeaponIcon());

            teamMember.setList(getMemberField(member));
            list.add(teamMember);
        }
        return list;
    }

    /**
     * 取队员信息Field
     */
    private List<FiedValue> getMemberField(Member member) {
        List<FiedValue> fieldValues = new ArrayList<>();
        fieldValues.add(new FiedValue(31, 2, member.getLevel()));
        fieldValues.add(new FiedValue(1, 4, member.getName()));
        fieldValues.add(new FiedValue(29, 1, member.getSex()));
        fieldValues.add(new FiedValue(44, 2, member.getMenpai()));
        fieldValues.add(new FiedValue(86, 7, member.getIcon()));
        fieldValues.add(new FiedValue(75, 3, member.getZhanji()));
        fieldValues.add(new FiedValue(81, 4, roleService.getFamilyName(member.getMenpai())));
        fieldValues.add(new FiedValue(33, 4, member.getParty()));
        fieldValues.add(new FiedValue(341, 1, member.getFlyStatus()));
        return fieldValues;
    }

    /**
     * 刷新队伍列表
     */
    public void updateTeamList(Role role) {
        Team team = getTeam(role.getRoleId());
        if (team != null) {
            RespUpdateTeamList respUpdateTeamList = new RespUpdateTeamList();
            respUpdateTeamList.setList(getTeamMemberList(team));
            for (Member member : team.getList()) {
                if (!member.isInTeam()) {
                    continue;
                }
                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getUid());
                MessagePusher.pushMessage(memberRole, respUpdateTeamList);
            }
        }
    }

    /**
     * 队伍成员刷新列表
     */
    private List<TeamMemberEX> getTeamMemberListEX(Team team) {
        List<TeamMemberEX> list = new ArrayList<>();
        team.getList().forEach(member -> {
            TeamMemberEX teamMember = new TeamMemberEX();
            teamMember.setGid(member.getGid());
            teamMember.setCard_name(member.getCardName());
            teamMember.setIcon(member.getIcon());
            teamMember.setSuit_icon(member.getSuitIcon());
            teamMember.setWeapon_icon(member.getWeaponIcon());
            teamMember.setRoleId(member.getRoleId());
            if (!member.isInTeam()) {
                teamMember.setStatus((byte) 2);
            }
            teamMember.setList(getMemberField(member));
            list.add(teamMember);
        });
        return list;
    }

    public void updateTeamListEX(Team team) {
        List<TeamMemberEX> list = getTeamMemberListEX(team);
        RespUpdateTeamListEX respUpdateTeamListEX = new RespUpdateTeamListEX();
        respUpdateTeamListEX.setList(list);
        for (Member member : team.getList()) {
            Role memberRole = roleService.getOnlinePlayer(member.getUid());
            MessagePusher.pushMessage(memberRole, respUpdateTeamListEX);
        }
    }

    /**
     * 广播给队伍中的人员
     *
     * @param role
     */
    public void updateTeamListEX(Role role) {
        Team team = getTeam(role.getRoleId());
        if (team != null) {
            // 广播新加入的队员信息
            updateTeamListEX(team);
        } else {
            RespUpdateTeamListEX respUpdateTeamListEX = new RespUpdateTeamListEX();
            respUpdateTeamListEX.setList(new ArrayList<>());
            MessagePusher.pushMessage(role, respUpdateTeamListEX);
        }
    }

    /**
     * 发送队长守护 给队伍
     */
    public void sendGuardToTeam(Role leader, Team team) {
        for (Member member : team.getList()) {
            if (member.isInTeam()) {
                Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getUid());
                MessagePusher.pushMessage(memberRole, guardService.getFightGuard(leader, 5 - team.getList().size()));
            }
        }
    }

    /**
     * 队伍间广播成员变动消息
     */
    public void sendTeamChangeMsg(Team team, String msg) {
        if (team == null) {
            return;
        }
        RespNotifyMisc respNotifyMisc = new RespNotifyMisc(msg);
        for (Member member : team.getList()) {
            Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getUid());
            MessagePusher.pushMessage(memberRole, respNotifyMisc);
        }
    }

    /**
     * 给新队员广播其他队员信息  Todo 更新好友度的
     */
    private void sendMemberIn(Team team, Role joinRole) {
        for (Member Member : team.getList()) {
            Role teamRole = SpringUtils.getRoleService().getOnlinePlayer(Member.getUid());
            if (teamRole == null) {
                continue;
            }
            if (teamRole.getRoleId() != joinRole.getRoleId()) {
                memberIn(teamRole, joinRole);
            }
        }
    }


    /**
     * 给新队员广播其他队员信息 TODO 把队员加到陌生人列表
     */
    private void sendJoinSuccess(Team team, Role joinRole) {
        for (Member member : team.getList()) {
            Role teamRole = SpringUtils.getRoleService().getOnlinePlayer(member.getUid());
            if (teamRole == null) {
                continue;
            }
            if (teamRole.getRoleId() != joinRole.getRoleId()) {
                JoinSuccess(teamRole, joinRole);
            }
        }
    }

    /**
     * 队伍间广播队伍成员外观
     */
    public void sendAppearFormTeam(Team team) {
        for (Member member : team.getList()) {
            // 广播队伍成员外观
            Role memberRole = roleService.getOnlinePlayer(member.getUid());
            for (Member oMember : team.getList()) {
                Role appearRole = roleService.getOnlinePlayer(oMember.getUid());
                broadcastService.updateAppearance(memberRole, appearRole);
            }
        }
    }
    /**
     * 离队人员看 之前队伍成员外观
     */
    private void sendTeamFormLeave(Team team,Role role) {
        Role memberRole = roleService.getOnlinePlayer(role.getUid());
        for (Member oMember : team.getList()) {
            Role appearRole = roleService.getOnlinePlayer(oMember.getUid());
            broadcastService.updateAppearance(memberRole, appearRole);
        }
    }

    /**
     * 取出附近信息
     */
    public List<AroundInfo> getAroundInfo(Role role, boolean isTeam) {
        if (role == null) {
            return new ArrayList<>();
        }
        Pos position = role.getPos();
        ConcurrentHashSet<Integer> set = SpringUtils.getMapService().getRoleIds(new GroupMapParam(role), position.getMapId());
        List<AroundInfo> infoList = new ArrayList<>();
        int i = 0;
        for (Integer roleId : set) {
            Role tempRole = roleService.getOnlinePlayer(roleId);
            if (tempRole == null){
                continue;
            }
            if (tempRole.getPos().getMapId() == SpringUtils.getBean(KuafuShidaoService.class).mapId){
                String temp = SpringUtils.getBean(ShiDaoHandler.class).getLevelRange(tempRole);
                String str = SpringUtils.getBean(ShiDaoHandler.class).getLevelRange(role);
                if (!str.equals(temp)){
                    continue;
                }
            }
            if (tempRole == null || tempRole.getRoleId() == role.getRoleId()) {
                continue;
            } else if (isTeam) {//取出周围队伍队长信息
                Team team = getTeam(tempRole.getRoleId());
                if (team == null || !team.isLeader(tempRole.getRoleId()) || team.getList().size() >= 5) {
                    continue;
                } else {
                    AroundInfo aroundInfo = new AroundInfo();
                    aroundInfo.setIcon(tempRole.getRoleIcon());
                    aroundInfo.setTeamMembersCount((byte) team.getList().size());
                    List<FiedValue> list = newTeamService.packTeamFied(tempRole);
                    aroundInfo.setList(list);
                    infoList.add(aroundInfo);
                }
            } else {//取出周围玩家信息
                List<FiedValue> list = newTeamService.packTeamFied(tempRole);
                AroundInfo aroundInfo = new AroundInfo();
                aroundInfo.setIcon(tempRole.getRoleIcon());
                aroundInfo.setList(list);
                infoList.add(aroundInfo);
            }
            i++;
            if (i >= 20) {
                break;
            }
        }
        return infoList.size() >= 1 ? infoList : null;
    }

    /**
     * 取出附近人数
     */
    private NutMap getAroundPlayerNum(Role role) {
        NutMap nutMap = NutMap.NEW();
        Pos position = role.getPos();
        ConcurrentHashSet<Integer> set = SpringUtils.getMapService().getRoleIds(new GroupMapParam(role), position.getMapId());
        if (set == null) {
            nutMap.setv("leaderNum", 0);
            nutMap.setv("playerNum", 0);
            return nutMap;
        }
        short playerNum = 0;
        short leaderNum = 0;
        for (Integer roleId : set) {
            Role tempRole = roleService.getOnlinePlayer(roleId);
            if (tempRole == null || tempRole.getRoleId() == role.getRoleId()) {
                continue;
            } else {
                Team team = getTeam(tempRole.getRoleId());
                if (team == null) {
                    playerNum++;
                } else if (team.isLeader(tempRole.getRoleId())) {
                    leaderNum++;
                }
            }
        }
        nutMap.setv("leaderNum", leaderNum);
        nutMap.setv("playerNum", playerNum);
        return nutMap;
    }

    /**
     * 判断玩家是否是队伍的队长，是的话返回true
     *
     * @param role
     * @return
     */
    public boolean isTeamLeader(Role role) {
        /** 暂时第2个参数没有用到，所以这样写*/
        Team team = getTeam(role.getRoleId());

        /**队伍不存在，很明显返回false*/
        if (team == null) {
            return false;
        }

        return team.isLeader(role.getRoleId());
    }
    /**
     * 判断玩家是否是队伍的队长，是的话返回true
     * @param
     * @return
     */
    public boolean isTeamLeader(int roleId) {
        /** 暂时第2个参数没有用到，所以这样写*/
        Team team = getTeam(roleId);

        /**队伍不存在，很明显返回false*/
        if (team == null) {
            return false;
        }

        return team.isLeader(roleId);
    }

    /**
     * 判断如果是队长，则给整个队伍发，否则只需要给操作的玩家发
     */
    public void pushMessage(Role role, Message message) {
        if (isTeamLeader(role)) {
            pushMessageToTeam(role, message);
        } else {
            MessagePusher.pushMessage(role, message);
        }
    }

    /**
     * 给玩家队伍推送信息
     */
    private void pushMessageToTeam(Role role, Message message) {
        /** 暂时第2个参数没有用到，所以这样写*/
        Team team = getTeam(role.getRoleId());


        pushMessageToTeam(team, message);
    }

    /**
     * 给队伍推送信息
     *
     * @param team
     * @param message
     */
    public void pushMessageToTeam(Team team, Message message) {
        if (team == null || message == null) {
            return;
        }

        List<Member> members = team.getList();
        /**遍历队伍所有成员，推送*/
        for (Member member : members) {
            if (member == null) {
                continue;
            }
            /**暂离成员收不到信息*/
            if (member.isInTeam() == false) {
                continue;
            }

            Role membeRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
            MessagePusher.pushMessage(membeRole, message);
        }
    }

    /**
     * 获得队伍人数
     */
    public int getTeamCount(Role role) {
        Team team = getTeam(role.getRoleId());
        return getTeamCount(team);
    }

    /**
     * 获得队伍人数
     */
    public int getTeamCount(Team team) {
        if (team == null) {
            return 0;
        }

        int count = 0;
        List<Member> members = team.getList();
        for (Member member : members) {
            if (member == null) {
                continue;
            }
            if (member.isInTeam() == false) {
                continue;
            }
//是否离线都不判断
            IoSession session = SessionUtils.getSession(member.getRoleId());
            if (session == null) {
                break;
            }
            Role tempRole = SessionUtils.getRoleBySession(session);
            if (tempRole == null) {
                break;
            }
            count++;
        }

        return count;
    }

    /**
     * 是否在队伍中
     */
    public boolean isInTeam(Role role) {
        Team team = getTeam(role.getRoleId());
        if (team == null) {
            return false;
        }

        for (Member member : team.getList()) {
            if (member.getRoleId() == role.getRoleId()) {
                return member.isInTeam();
            }
        }

        return false;
    }

    /**
     * 检测成员，返回不满足成员的名字，多个名字中间用、分隔
     */
    public String checkMember(Role role, Predicate<Role> predicate) {
        Team team = getTeam(role.getRoleId());
        if (team == null) {return null;}

        return checkMember(team, predicate);
    }

    /**
     * 检测成员，返回不满足成员的名字，多个名字中间用、分隔
     */
    public String checkMember(Team team, Predicate<Role> predicate) {
        StringBuilder stringBuilder = null;
        for (Member member : team.getList()) {
            if (member == null) {
                continue;
            }
            /**暂离的不用判断*/
            if (member.isInTeam() == false) {
                continue;
            }

            Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
            if (memberRole == null) {
                continue;
            }

            if (predicate.test(memberRole)) {
                if (stringBuilder == null) {
                    stringBuilder = new StringBuilder();
                }
                if (stringBuilder.length() > 0) {
                    stringBuilder.append("、");
                }
                stringBuilder.append(memberRole.getName());
            }
        }

        return stringBuilder != null ? stringBuilder.toString() : null;
    }

    /**
     * 队伍所有成员进行操作
     * 在没有修改玩家数据的方法才调用，有修改玩家数据时调用 memberHandleThreadLocal
     */
    public void memberHandle(Team team, Consumer<Role> consumer) {
        for (Member member : team.getList()) {
            if (member == null) {
                continue;
            }
            /**暂离的不用判断*/
            if (!member.isInTeam()) {
                continue;
            }

            Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
            if (memberRole == null) {
                continue;
            }

            consumer.accept(memberRole);
        }
    }

    /**
     * 队伍所有成员进行操作。
     * 成员的操作给到成员对应的线程操作，保证线程安全。
     * 队长在最后在当前线程操作。
     * 一般只在修改玩家数据的方法才调用
     */
    public void memberHandleThreadLocal(Team team, Consumer<Role> consumer) {
        Role leaderRole = null;
        for (Member member : team.getList()) {
            if (member == null) {
                continue;
            }
            /**暂离的不用判断*/
            if (!member.isInTeam()) {
                continue;
            }

            Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
            if (memberRole == null) {
                continue;
            }

            if (team.isLeader(memberRole.getRoleId())) {
                leaderRole = memberRole;
            } else {
                ThreadLocalUtil.addLocalTask(memberRole, () -> consumer.accept(memberRole));
            }
        }

        consumer.accept(leaderRole);
    }

    /**
     * 玩家组队时，队伍所有成员操作，由队长调用
     * 但不保证线程安全。
     * 一般在没有修改玩家数据时调用
     * 没组队时，个人操作
     */
    public void memberHandle(Role role, Consumer<Role> consumer) {
        if (isInTeam(role) && isTeamLeader(role)) {
            Team team = getTeam(role.getRoleId());
            memberHandle(team, consumer);
        } else {
            consumer.accept(role);
        }
    }

    /**
     * 玩家组队时，队伍所有成员操作，由队长调用
     * 成员的操作给到成员对应的线程操作，保证线程安全。
     * 队长在最后在当前线程操作。
     * 一般只在修改玩家数据的方法才调用
     * 没组队时，个人操作
     */
    public void memberHandleThreadLocal(Role role, Consumer<Role> consumer) {
        if (isInTeam(role) && isTeamLeader(role)) {
            Team team = getTeam(role.getRoleId());
            memberHandleThreadLocal(team, consumer);
        } else {
            consumer.accept(role);
        }
    }

    /**
     * 获得暂离成员名字
     */
    public String getNotInTeam(Team team) {
        StringBuilder stringBuilder = null;
        for (Member member : team.getList()) {
            if (member == null) {
                continue;
            }
            /**不是暂离的不用判断*/
            if (member.isInTeam()) {
                continue;
            }

            if (stringBuilder == null) {
                stringBuilder = new StringBuilder();
            }
            if (stringBuilder.length() > 0) {
                stringBuilder.append("、");
            }
            stringBuilder.append(member.getName());
        }

        return stringBuilder != null ? stringBuilder.toString() : null;
    }

    public void newMemberJoinTeam(Team team, Role leader, Role role, String opType) {
        /**
         * 清除队员申请列表
         */
        cleanTeamRequest(leader, opType, role.getName());

        /**
         * 第一个发  队员的状态广播
         */
        broadcastService.sendTitleInfo(role);
        broadcastService.sendTitleInfo(leader);
        /**
         * 第二个发  队员的信息给队长
         */
        sendJoinSuccess(team, role);
        /**
         * 第三个发  队员广播外观
         */
        broadcastService.sendUpdateAppear(role);

        /**
         * 第五个发  4119 队伍包 广播
         */
        updateTeamList(role);
        /**
         * 第六个发  4121 队伍包 广播
         */
        updateTeamListEX(role);
        /**
         * 第七个发  守护加入包
         */
        sendGuardToTeam(leader, team);
        /**
         * 第八个发  队伍成员外观包
         */
        sendAppearFormTeam(team);
        /**
         * 发送新加入成员包给队长
         */
        sendMemberIn(team, role);

        MessagePusher.pushMessage(role, new RespNotifyMiscEx("你加入#Y" + leader.getName() + "#n的队伍。"));
        sendTeamChangeMsg(team, "#Y#<" + role.getName() + "#>#n加入了队伍。");
    }

    /**
     * 接受申请或者接受邀请
     */
    public void accept(IoSession session, ReqAccept reqAccept) {
        //接收申请session为队长  接收邀请 session为队员
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        NutMap sessionData = SessionDataUtils.getData(role);

        BroadcastService broadcastService = SpringUtils.getBean(BroadcastService.class);
        Team team = null;
        if (reqAccept.getType().equals("request_join")) {
            team = getTeam(role.getRoleId());
            //同意别人进队
            Role newTeamMember = roleService.getOnlinePlayer(reqAccept.getName());
            newTeamService.agreeInviteJoinTeam(newTeamMember,role.getRoleId(),reqAccept.getType());
        } else if (reqAccept.getType().equals("invite_join")) {//队员同意邀请
            // 角色同意进入对方队伍
            int roleId = sessionData.getInt(Const.sessionTeam + reqAccept.getName());
            newTeamService.agreeInviteJoinTeam(role,roleId,reqAccept.getType());
        } else if (reqAccept.getType().equals("party")) {//同意入帮
            logger.info("同意入帮");
            SpringUtils.getBean(PartyService.class).agreeJoinParty(role, reqAccept.getName());
        }
    }

    public Member getMember(Role role) {
        Member member = Member.valueOf(role);
        member.setCardName(role.getChangeCard() != null ? role.getChangeCard().getName() : null);
        return member;
    }

    /**
     * 创建队伍
     */
    public Team createTeam(Role role) {

      // broadcastService.sendTitleInfo(role);
        RespClearnAllRequest respClearnAllRequest = new RespClearnAllRequest();
        respClearnAllRequest.setType("invite_join");
        MessagePusher.pushMessage(role, respClearnAllRequest);

        // 判断是否已经有了队伍
        if (getTeam(role.getRoleId()) != null) {
            return null;
        }


        Team team = new Team();
        team.setCreateTime(new Date());

        Member member = getMember(role);
        ArrayList<Member> arrayList = new ArrayList<>();
        arrayList.add(member);
        team.setList(arrayList);
        // 广播给地图中的玩家

        // 添加守护信息
        team.setShouhus(SpringUtils.getBean(GuardService.class).getGuardMembers(role, 5 - team.getList().size()));
        sendGuardToTeam(role, team);
        //team信息存入redis
        saveTeam(team);
        SpringUtils.getBroadcastService().sendTitleInfo(role);
       /////单独给自己发一下避免协议分包错误
        Message titleInfo = broadcastService.getTitleInfo(role);
        MessagePusher.pushMessage(role, titleInfo);

        updateTeamList(role);
        // 广播新进入的成员的信息
        updateTeamListEX(role);

        RespNotifyMisc notifyMisc = new RespNotifyMisc();
        notifyMisc.setMsg("你组建了一支队伍。");
        int currTime = new Long(System.currentTimeMillis() / 1000).intValue();
        notifyMisc.setTime(currTime);
        MessagePusher.pushMessage(role, notifyMisc);
        SpringUtils.getBean(DiFuShiDaoPKService.class).doAfterAddTeam(role, team);
        return team;
    }

    /**
     * 拒绝
     */
    public void reject(IoSession session, ReqReject reqReject) {
        Role role = SessionUtils.getRoleBySession(session);
        switch (reqReject.getType()) {
            case "request_join": {
                Role teamRole = roleService.getOnlinePlayer(reqReject.getName());
                MessagePusher.pushMessage(teamRole, new RespMsg("对方拒绝了你的申请。"));
                break;
            }
            case "party":
                SpringUtils.getBean(PartyService.class).refuseJoinParty(role, reqReject.getName());
                break;
            case "invite_join": {
                Role teamRole = roleService.getOnlinePlayer(reqReject.getName());
                MessagePusher.pushMessage(teamRole, new RespMsg(role.getName() + "拒绝了你的邀请！"));
                break;
            }
        }
        cleanTeamRequest(role, reqReject.getType(), reqReject.getName());
    }

    private void cleanTeamRequest(Role role, String type, String name) {
        RespClearnRequest respClearnRequest = new RespClearnRequest();
        respClearnRequest.setType(type);
        ArrayList<String> names = new ArrayList<>();
        names.add(name);
        respClearnRequest.setNames(names);
        MessagePusher.pushMessage(role, respClearnRequest);
    }


    private void changeLeader(Role leader, int roleId) {
        Team team = getTeam(roleId);
        if (team == null) {
            return;
        }

        if (!team.isLeader(leader.getRoleId())) {
            return;
        }

        /**产生一个转移队长事件*/
        EventDispatcher.getInstance().fireEvent(new TeamChangeLeaderEvent(EventType.TEAM_CHANGE_LEADER, leader, team.getList()));

        ArrayList<Member> members = team.getList();
        Member toLeader = null;
        int index = 0;
        for (int i = 0; i < members.size(); i++) {
            if (roleId == members.get(i).getRoleId()) {
                index = i;
                toLeader = members.get(i);
                break;
            }
        }
        Member oldLeader = members.get(0);
        members.set(index, oldLeader);
        members.set(0, toLeader);
        team.setList(members);
        saveTeam(team);
        BroadcastService broadcastService = SpringUtils.getBean(BroadcastService.class);
        team = getTeamByTeamId(team.getId());
        Role newLeader = roleService.getOnlinePlayer(team.getLeaderUid());

        team.setShouhus(SpringUtils.getBean(GuardService.class).getGuardMembers(newLeader, 5 - team.getList().size()));
        sendGuardToTeam(newLeader, team);
        broadcastService.sendTitleInfo(newLeader);

        broadcastService.sendTitleInfo(leader);
        updateTeamListEX(newLeader);
        updateTeamList(newLeader);

        Role tmpRole = SpringUtils.getRoleService().getOnlinePlayer(roleId);

//        int x=tmpRole.getPos().getX();
//        int y=tmpRole.getPos().getY();
//        int id=tmpRole.getPos().getMapId();
//        int dir=tmpRole.getPos().getDir();
//        EventDispatcher.getInstance().fireEvent(new LeaveMapEvent(EventType.LEAVE_MAP, tmpRole, id));
//        tmpRole.setPos(x, y, dir, id);
//        /**产生一个进入地图事件*/
//        EventDispatcher.getInstance().fireEvent(new EnterMapEvent(EventType.ENTER_MAP, tmpRole));
        MessagePusher.pushMessage(tmpRole, new RespNotifyMiscEx("你成为了队长。"));
        sendAppearFormTeam(team);
        sendTeamChangeMsg(team, "#Y#<" + newLeader.getName() + "#>#n成为队长。");
    }

    /**
     * 变更队长
     */
    public void changeLeader(IoSession session, ReqChangeTeamLeader reqChangeTeamLeader) {
        String roleIdStr = reqChangeTeamLeader.getRoleId();
        int roleId = Integer.parseInt(roleIdStr);
        Role role = SessionUtils.getRoleBySession(session);

        changeLeader(role, roleId);
    }

    /**
     * 队伍移动
     */
    public void otherMove(IoSession session, ReqOtherMoveTo moveTo) {
        Role leader = SessionUtils.getRoleBySession(session);
        Role otherRole = roleService.getOnlinePlayer(moveTo.getRoleId());
        if (otherRole == null) {//宠物 或者跟宠?
            Pet pet = leader.getPetBox().getPetByPetId(moveTo.getRoleId());
            if (pet == null) {
                return;
            }
            RespPositionMove move = new RespPositionMove();
            move.setRoleId(pet.getId());
            move.setX(moveTo.getX());
            move.setY(moveTo.getY());
            move.setDir(leader.getPos().getDir());
            SceneManager.INSTANCE.sendMessages(leader, move);
        } else {
            if(leader.getPos().getMapId() == otherRole.getPos().getMapId()){
                SceneManager.INSTANCE.movePosition(otherRole);
                Pos pos = otherRole.getPos();
                pos.setX(moveTo.getX());
                pos.setY( moveTo.getY());
                pos.setDir((byte)moveTo.getDir());
                otherRole.setPos(pos);
            }
        }
    }

    /**
     * 一键召集
     */
    public void operTeleport(IoSession session, ReqOperTeleportItem item) {
        RespConfirm RespConfirm = new RespConfirm();
        RespConfirm.setTips("队长召集你归队。");
        Role role = SessionUtils.getRoleBySession(session);
        if (SpringUtils.getBean(DugeonTaskHandler.class).isInDugeon(role)) {
            MessagePusher.notify2Player(role, I18nId.PMT_1528);
            return ;
        }
        Team team = getTeam(role.getRoleId());
        if (team == null) {
            return;
        }
        for (Member member : team.getList()) {
            if (member.isInTeam()) {
                continue;
            }
            Role teamRole = roleService.getOnlinePlayer(member.getUid());
            //如果是一个固定队的话 直接归队，不在发通知。
            //这里判断固定队特权
            String roleFixed = role.getFixedTeam()==null?"":role.getFixedTeam();
            String joinRoleFixed = teamRole.getFixedTeam();
            if(StringUtils.isNotEmpty(roleFixed) && roleFixed.equals(joinRoleFixed)){
                //如果是同一个固定队的话。 查看队员的 固定队设置 是否打开 被邀请自动通过
                Map<String, Integer> setMap = teamRole.getExtendBox().getSetMap();
                if(setMap.containsKey("ft_recruit")){
                    Integer setMap1 = setMap.get("ft_recruit");
                    if(setMap1 == 1){
                        returnTeam(teamRole);
                        //固定队
                        MessagePusher.pushMessage(teamRole, new RespMsg("你开启了固定队伍特权5，其他成员召集#R归队#n自动通过"));
                        continue;
                    }
                }

            }
            teamRole.setConfirm(new ReturnTeamConfirm());
            MessagePusher.pushMessage(teamRole, RespConfirm);
        }
    }

    /**
     * 暂离队伍
     */
    public void leaveTemp(IoSession session, ReqLeaveTempTeam reqLeaveTempTeam) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) return;
        Team team = getTeam(role.getRoleId());
        if (team == null) {
            return;
        }
        if (!SpringUtils.getBean(ShiDaoHandler.class).leaveMonmentConfirm(role)) {
            return;
        }

      //  BroadcastService broadcastService = SpringUtils.getBean(BroadcastService.class);

        updateTeam(1, role.getRoleId());
//        int x=role.getPos().getX();
//        int y=role.getPos().getY();
//        int id=role.getPos().getMapId();
//        int dir=role.getPos().getDir();
//        EventDispatcher.getInstance().fireEvent(new LeaveMapEvent(EventType.LEAVE_MAP, role, id));
//        role.setPos(x, y, dir, id);
//        /**产生一个进入地图事件*/
//        EventDispatcher.getInstance().fireEvent(new EnterMapEvent(EventType.ENTER_MAP, role));
        updateTeamList(role);
        updateTeamListEX(role);
        broadcastService.sendTitleInfo(role);
        RespUpdateTeamList respUpdateTeamList = new RespUpdateTeamList();
        respUpdateTeamList.setList(new ArrayList<>());
        MessagePusher.pushMessage(session, respUpdateTeamList);
        sendTeamChangeMsg(team, "#Y#<" + role.getName() + "#>#n暂离了队伍。");


        broadcastService.sendUpdateAppear(role);
        /**产生一个暂离队伍事件*/
        EventDispatcher.getInstance().fireEvent(new TeamLeaveMomentEvent(EventType.TEAM_LEAVE_MOMENT, role));
        sendAppearFormTeam(team);
//        EventDispatcher.getInstance().fireEvent(new LeaveMapEvent(EventType.LEAVE_MAP, role, id));
//        role.setPos(x, y, dir, id);
//        /**产生一个进入地图事件*/
//        EventDispatcher.getInstance().fireEvent(new EnterMapEvent(EventType.ENTER_MAP, role));
    }

    /**
     * 踢出队伍
     */
    public void kickOutTeam(IoSession session, ReqKickOutTeam reqKickOutTeam) {
        try {
            String name = reqKickOutTeam.getName();
            long uid = SpringUtils.getPlayerService().getUidBy(name);
            leave(new RoleView(uid), true);
        } catch (Exception e) {
            Role role = SessionUtils.getRoleBySession(session);
            Team team = SpringUtils.getBean(TeamService.class).getTeam(role.getRoleId());
            for (Member member : team.getList()) {
                if (member.getName().equals(reqKickOutTeam.getName())) {
                    team.getList().remove(member);
                    break;
                }
            }
            updateTeamList(role);
            updateTeamListEX(role);
        }
    }

    /**
     * 刷新请求信息
     */
    public void refreshRequestInfo(IoSession session, ReqRefreshRequestInfo reqRefreshRequestInfo) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        NutMap nutMap = getAroundPlayerNum(role);
        RespAround RespAround = new RespAround();
        RespAround.setLeaderNum((short) nutMap.getInt("leaderNum"));
        RespAround.setPlayerNum((short) nutMap.getInt("playerNum"));
        MessagePusher.pushMessage(session, RespAround);
    }

    /**
     * 队长拉去队员或者跟宠到自己身边
     */
    public void shift(IoSession session, ReqShift reqShift) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        Pos p = role.getPos();
        int id = reqShift.getId();
        Role member = roleService.getOnlinePlayer(id);
        /**队伍成员移动到角色身旁*/
        if (member != null && isInTeam(member) && isInTeam(role) && getTeam(member.getRoleId()).getId()==getTeam(role.getRoleId()).getId()) {
            Pos pos = member.getPos();
            pos.setX(p.getX());
            pos.setY(p.getY());
            member.save();
            /**拉取队员移动*/
            fetchMember(role, member);
        } else {
            /**宠物或者跟宠 或者跟随NPC移动到角色身旁*/
            Pet pet = role.getPetBox().getPetByPetId(id);
            if (pet != null) {
                RespPositionMove move = new RespPositionMove();
                move.setRoleId(pet.getId());
                move.setX(reqShift.getX());
                move.setY(reqShift.getY());
                move.setDir((byte) reqShift.getDir());
                SceneManager.INSTANCE.sendMessages(role, move);
            }
        }
    }


    /**
     * 拉取队员回到自己身边 如果不在一个地图 切换地图 如果在一个地图 移动
     */
    private void fetchMember(Role leader, Role role) {
        int leaderMapId = leader.getPos().getMapId();
        int roleMapId = role.getPos().getMapId();
        //System.out.println("队长ID："+leaderMapId);
        //System.out.println("队员ID："+roleMapId);
        /**如果跟队长不在一个地图里面*/
        if (leaderMapId != roleMapId) {
            //System.out.println("切图队长ID："+leaderMapId);
            /**产生一个离开地图事件*/
            EventDispatcher.getInstance().fireEvent(new LeaveMapEvent(EventType.LEAVE_MAP, role, roleMapId));

            role.setPos(leader.getPos().getX(), leader.getPos().getY(), leader.getPos().getDir(), leader.getPos().getMapId());
            /**产生一个进入地图事件*/
            EventDispatcher.getInstance().fireEvent(new EnterMapEvent(EventType.ENTER_MAP, role,roleMapId));
            //System.out.println("切图队员ID："+roleMapId);
        } else {
            /**如果在一个地图 移动到队长身边*/
            SceneManager.INSTANCE.movePosition(role);
            //System.out.println("跟随+++++++++++++");
        }
    }

    /**
     * 申请加入
     */
    public void requestJoin(IoSession session, ReqRequestJoin requestJoin) {
        Role role = SessionUtils.getRoleBySession(session);
        // 判定玩家是否已经有队伍
        /**如果申请加入的队长名是自己 那么就是创建队伍*/
        if (requestJoin.getName().equals(role.getName())) {
            // 创建队伍信息
            createTeam(role);
        } else if (requestJoin.getType().equals("request_join")) {
            //申请加入队伍
            newTeamService.requestJoin(role,requestJoin.getRoleId());
        } else if (requestJoin.getType().equals("invite_join")) {
            //邀请别人加入队伍
            newTeamService.inviteJoinTeam(role,requestJoin.getRoleId());
        } else if (requestJoin.getType().equals("request_team_leader")) {
            //申请带队
            Team team = getTeam(role.getRoleId());
            if (team == null) {
                return;
            }
            Role leader = roleService.getOnlinePlayer(team.getLeaderUid());
            if (leader == null) {
                return;
            }
            RespAroundInfo respAroundInfo = new RespAroundInfo();
            respAroundInfo.setInviteName(role.getName());
            respAroundInfo.setType("request_team_leader");
            MessagePusher.pushMessage(leader, respAroundInfo);
            MessagePusher.pushMessage(session, new RespMsg("你的申请已发送。"));

            //这里判断固定队特权
            String roleFixed = role.getFixedTeam()==null?"":role.getFixedTeam();
            String joinRoleFixed = leader.getFixedTeam();
            if(StringUtils.isNotEmpty(roleFixed) && roleFixed.equals(joinRoleFixed)){
                //如果是同一个固定队的话。 查看队员的 固定队设置 是否打开 申请带队直接通过
                Map<String, Integer> setMap = leader.getExtendBox().getSetMap();
                if(setMap.containsKey("ft_lead_team")){
                    Integer setMap1 = setMap.get("ft_lead_team");
                    if(setMap1 == 1){
                        SpringUtils.getTeamService().acceptRequestTeamLeader(leader,role.getRoleId());
                        //固定队
                        MessagePusher.pushMessage(leader, new RespMsg("你开启了固定队伍特权6，其他成员申请#R带队#n自动通过"));
                        return;
                    }
                }
            }
            RespConfirm confirm = new RespConfirm();
            confirm.setTips("#Y" + role.getName() + "#n申请成为队长，是否同意？");
            confirm.setConfirm_type("reject_count_down");
            confirm.setDown_count(30);
            confirm.setShow_dlg_mode((byte) 3);
            MessagePusher.pushMessage(leader, confirm);

            leader.setConfirm(new RequestTeamLeaderConfirm(role.getRoleId()));
            SpringUtils.getBean(ServerService.class).getScheduledExecutorService().schedule(new Runnable() {
                @Override
                public void run() {
                    RequestTeamLeaderConfirm requestTeamLeaderConfirm = ((RequestTeamLeaderConfirm)leader.getConfirm());
                    if (requestTeamLeaderConfirm.isAgree()){
                        return;
                    }
                    SpringUtils.getTeamService().acceptRequestTeamLeader(leader,requestTeamLeaderConfirm.getRequestId());
                }
            },30, TimeUnit.SECONDS);

        } else if (requestJoin.getType().equals("party_remote")) {//申请加入帮派
            SpringUtils.getBean(PartyService.class).reqJoinParty(role, requestJoin.getName());
        } else if (requestJoin.getType().equals("party_one_key")) {//申请加入帮派
            SpringUtils.getBean(PartyService.class).oneKeyJoin(role);
        }
    }

    /**
     * 获得队伍中所有玩家名字
     */
    public String getMemberNames(Team team) {
        if (team == null) {
            return null;
        }

        StringBuilder stringBuilder = null;
        for (Member member : team.getList()) {
            if (member == null) {
                continue;
            }
            /**暂离的不用判断*/
            if (member.isInTeam() == false) {
                continue;
            }

            if (stringBuilder == null) {
                stringBuilder = new StringBuilder();
            }
            if (stringBuilder.length() > 0) {
                stringBuilder.append("、");
            }
            stringBuilder.append(member.getName());
        }

        return stringBuilder != null ? stringBuilder.toString() : null;
    }

    /**
     * 同意队员的带队申请
     */
    public void acceptRequestTeamLeader(Role leader, int requestId) {
        Role role = SpringUtils.getRoleService().getOnlinePlayer(requestId);
        if (role == null) {
            return;
        }

        changeLeader(leader, requestId);


    }

    /**
     * 在组队却不是队长
     */
    public boolean isInTeamAndNotLeader(Role role) {
        return isInTeam(role) && !isTeamLeader(role);
    }

    /**
     * 没在组队或者在组队同时是队长
     */
    public boolean isNotInTeamOrLeader(Role role) {
        return !isInTeam(role) || isTeamLeader(role);
    }

    /**
     * 获得角色所在队伍最大等级
     */
    public int getMaxRoleLevelInTeam(Role role) {
        Team team = getTeam(role.getRoleId());
        return getMaxRoleLevelInTeam(team);
    }

    private int getMaxRoleLevelInTeam(Team team) {
        AtomicInteger maxLevel = new AtomicInteger();
        memberHandle(team, memberRole -> {
            if (memberRole.getLevel() > maxLevel.get()) {
                maxLevel.set(memberRole.getLevel());
            }
        });

        return maxLevel.get();
    }

    /**
     * 是否可以发送邀请信息。判断当前人等级，当前人地图， 邀请人是否在监狱，是否在任务。
     * @param role
     * @param id
     * @return
     */
    public boolean isSendInviteTeam(Role role,int id){
        if(role.getLevel()<20){
            MessagePusher.pushMessage(role, new RespMsg("20级后才能邀请加入队伍。"));
            return true;
        }
        Role joinRole = SpringUtils.getRoleService().getOnlinePlayer(id);
        if(joinRole == null){
            return true;
        }
        //这里判断所有不能组队的地方。

        //被邀请人是否在监狱
        if(SpringUtils.getBean(PkService.class).isInPrisonTime(joinRole)){
            return true;
        }

        Team team = getTeam(joinRole.getRoleId());
        //是否已经有队伍
        if(team != null){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("对方已有队伍！"));
            return true;
        }
        int map = role.getPos().getMapId();
        int joinMap = joinRole.getPos().getMapId();
        //增加 地府竞技场，如果两个人都在场内 则可以邀请队伍。。 也可以申请加入
        if(map == joinMap && map == 60007){
            return false;
        }
        //邀请人是否在特殊地图内

        if(StaticParam.notJOINTeamMAPIDS.contains(map)){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("正在任务，无法进行组队！"));
            return true;
        }
        //被邀请人是否在特殊地图内
        if(StaticParam.notJOINTeamMAPIDS.contains(joinMap)){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("正在任务，无法进行组队！"));
            return true;
        }
        return false;
    }
    /**
     * 是否可以 同意  对方进入队伍
     * @param role  当前同意的人
     * @param id    发出邀请的人
     * @return
     */
    public boolean isJoinTeam(Role role,int id){
        // 角色同意进入对方队伍
        //是否在试道内
        if(!SpringUtils.getBean(ShiDaoHandler.class).isAcceptJoinTeam(role, id)){
            return true;
        }
        //是否在地府试道内
        if(!SpringUtils.getBean(DiFuShiDaoService.class).isAcceptJoinTeam(role, id)){
            return true;
        }
        //是否在坐牢
        if(SpringUtils.getBean(PkService.class).isInPrisonTime(role)){
            return true;
        }
        Role joinRole = SpringUtils.getRoleService().getOnlinePlayer(id);
        if(SpringUtils.getBean(PkService.class).isInPrisonTime(joinRole)){
            return true;
        }
        if (!SpringUtils.getBean(DugeonTaskHandler.class).isAcceptJoinTeam(role, id)) {
            return true;
        }
        if (SpringUtils.getFightService().getFightByRoleId(role.getRoleId()) != null) {
            MessagePusher.pushMessage(role, new RespMsg("当前不能同意邀请。"));
            return true;
        }
        if (SpringUtils.getFightService().getFightByRoleId(id) != null) {
            MessagePusher.pushMessage(role, new RespMsg("对方当前无法接受同意邀请。"));
            return true;
        }
        //邀请人是否在特殊地图内
        int map = role.getPos().getMapId();
        if(Arrays.asList(StaticParam.notJOINTeamMAPIDS).contains(map)){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("正在任务，无法进行组队！"));
            return true;
        }
        //被邀请人是否在特殊地图内
        map = joinRole.getPos().getMapId();
        if(Arrays.asList(StaticParam.notJOINTeamMAPIDS).contains(map)){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("正在任务，无法进行组队！"));
            return true;
        }
        return false;
    }
}